# -*- coding: utf-8 -*-
from logger_setup import get_logger
import requests
import json
import net_tool
import yaml_tool

login_logger = get_logger("login")

try:
    cfg = yaml_tool.get_dict()
    account = cfg['account']
    userid = str(account['userid'])
    password = str(account['password'])
    net = cfg['net']
    url = str(net['url'])
except Exception as e:
    login_logger.warning('login初始化错误')
    login_logger.error(e)

info = None


def login():
    """登陆"""
    global info
    try:
        info = net_tool.get_userinfo()
        if info == True:
            return "已连接网络"
    except:
        return False
    href = info[0]
    userinfo = info[1]
    headers = {
        'Host': url[6:],
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0',
        'Referer': href,
        'Connection': 'keep-alive',
        'Accept-Language': 'zh-CN,zh;q=0.9',
    }
    data = {
        'userId': userid,
        'password': password,
        'service': '',
        'queryString': 'wlanuserip%3D' + userinfo["wlanuserip"] + '%26wlanacname%3D' + userinfo[
            "wlanacname"] + '%26ssid%3D%26nasip%3D' + userinfo["ssid_nasip"] + '%26snmpagentip%3D%26mac%3D' + userinfo[
                           "snmpagentip_mac"] + '%26t%3Dwireless-v2%26url%3D' + userinfo[
                           "wirelessv2_url"] + '%26apmac%3D%26nasid%3D' + userinfo["apmac_nasid"] + '%26vid%3D' +
                       userinfo["vid"] + '%26port%3D' + userinfo["port"] + '%26nasportid%3D' + userinfo["nasportid"],
        'operatorPwd': '',
        'operatorUserId': '',
        'validcode': '',
        'passwordEncrypt': 'false',
    }
    login_url = url + "/eportal/InterFace.do?method=login"
    # getonlineuserinfo_url = url + "/eportal/InterFace.do?method=getOnlineUserInfo"
    login_logger.info('login数据整理完成')
    try:
        response = requests.post(url=login_url, data=data, headers=headers)
        result = response.json()
        result_1 = json.dumps(response.json(), ensure_ascii=False)
        result1 = result_1.encode('ISO-8859-1')
        result1 = result1.decode('utf-8')
        print(result1)
        if '"result": "success"' in result1:
            userIndex = str(result['userIndex'])
            login_logger.info(f"登录成功,userindex为：{userIndex}")
            yaml_tool.repair_data(["net", "userIndex"], userIndex)
            return True
        else:
            message = str(result['message'])
            login_logger.info(f'登录失败，{message}')
            return False
    except Exception as e:
        login_logger.warning('发生错误')
        login_logger.error(e)